package com.aaa.gateway.filter;

import com.aaa.util.JwtUtil;
import com.aaa.vo.Result;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;




@Component
public class FrontLoginFilter  implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("#{'${discharged.path}'.split(',')}")
    private String[] pashs;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.获取请求路径
        String path = request.getPath().toString();
        System.out.println("path===="+path);
        if ("/login".equals(path)){
            return chain.filter(exchange);
        }
        if (Arrays.stream(pashs).parallel().anyMatch(path::contains)){
            return chain.filter(exchange);
        }
        //3.获取请求头
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.hasText(token)&& JwtUtil.verifyToken(token)&&redisTemplate.hasKey(token)){
            //刷新token时间
            redisTemplate.expire(token,30, TimeUnit.MINUTES);
            //4.放行
            return chain.filter(exchange);
        }
        Result<String> result=new Result<>(5001,"登录失效");
        //3.3作JSON转换
        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);

        //3.4调用bufferFactory方法,生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        //4.调用Mono中的just方法,返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
